<?php
final class Db {
    //db对象
    private static $instance;
    //数据库连接实例
    /**
     * 数据库连接实例
     * @var mysqli
     */
    protected $connect;
    final private function __construct ()
    {
    
    }
    final private function __clone()
    {
        $this->throwError('此对象不可以被克隆');
    }
    
    /**
     * 获取数据库连接对象
     * @param array $data
     * @return Db
     */
    public static function getInstance(array $data){
        if(self::$instance instanceof self){
            return self::$instance;
        }
        self::$instance = new self();
        self::$instance->connect($data);
        return self::$instance;
    }
    
    /**
     * 连接数据库
     * @param array $data
     */
    protected function connect(array $data = [])
    {
        try {
            if(empty($data['DB_HOST'])){
                $this->throwError('DB_HOST is null');
            }
            if(empty($data['DB_PORT'])){
                $this->throwError('DB_PORT is null');
            }
            if(empty($data['DB_USER'])){
                $this->throwError('DB_USER is null');
            }
            if(!isset($data['DB_PWD'])){
                $this->throwError('DB_PWD is null');
            }
            $this->connect = new mysqli("{$data['DB_HOST']}:{$data['DB_PORT']}" , $data['DB_USER'] , $data['DB_PWD']);
            return self::$instance;
        } catch (Exception $e) {
            $this->throwError($e->getMessage() , $e->getCode());
        }
    }
    
    public function query($sql = '')
    {
        return $this->connect->query($sql);
    }
    
    public function selectDb($dbName = '')
    {
        $this->connect->select_db($dbName);
        return self::$instance;
    }
    
    private function throwError($message = '',$code=1)
    {
        throw new Exception($message , $code);
    }
}
/*
$config = [
    'DB_HOST'=>'127.0.0.1',
    'DB_PORT'=>'3306',
    'DB_USER'=>'root',
    'DB_PWD'=>'',
];

$data = Db::getInstance($config)
    ->selectDb('li91_new')
    ->query('select * from li91_ad');

var_dump($data);*/